const { Router } = require('express')

const { User } = require('../model/User')

const { compare } = require('bcrypt')

const router = Router()

router.get('/', (req, res) => {
  res.redirect('/home')
})

router.get('/login', (req, res) => {
  res.render('admin/login')
})

router.post('/login', async (req, res) => {
  const { email, pwd } = req.body

  if (email.trim() === '' || pwd.trim() === '') {
    return res.status(400).render('admin/error', { msg: '邮箱或密码不能为空，请重新登录' })
  }
  // 访问数据库验证有没有这个人
  const user = await User.findOne({ email })

  // if (!user || user.pwd !== pwd) {
  if (!user || !(await compare(pwd, user.pwd))) {
    return res.status(400).render('admin/error', { msg: '邮箱或密码错误' })
  }

  req.session.user = user

  if (user.role === 'admin') {
    // 重定向
    return res.redirect('/admin/user/list')
  }
  res.redirect('/home/')
})

router.get('/logout', (req, res, next) => {
  req.session.destroy(err => {
    if (!err) {
      return res.redirect('/home/')
    }
    next(err)
  })
})

module.exports = { router }
